package com.guomao.up;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@WebServlet("/fileupload")
public class FileUpload extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        req.getServletContext().getMimeType("a.txt"); -> text/plain
        req.setCharacterEncoding("UTF-8");

        resp.setContentType("text/html;charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(req)) {
            PrintWriter writer = resp.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }


        DiskFileItemFactory df = new DiskFileItemFactory();

//        df.setSizeThreshold(1024*1024*5);
//        df.setRepository(new File("C://a.txt"));
        ServletFileUpload sfu = new ServletFileUpload(df);

        sfu.setHeaderEncoding("UTF-8");

        String path = "D:\\upload";

        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }


//        System.out.println("========================>1232455");
        try {
            List<FileItem> fileItems = sfu.parseRequest(req);
            if (fileItems != null && fileItems.size() > 0) {

                for (FileItem item : fileItems) {
                    if (!item.isFormField()) {

                        String name = item.getName();

                        String filename = new File(name).getName();

                        System.out.println(name + ":" + filename);


                        String filePath = path + File.separator + filename;

                        File dest = new File(filePath);


                        item.write(dest);

                        req.setAttribute("message",
                                "文件上传成功! 文件名: " + filename + "<br/>存储位置: " + filePath);

                    } else {
//                        String name = item.getName();
                        String fieldName = item.getFieldName();
//                        System.out.println(name + ":" + fieldName);

                        String parameter = req.getParameter(fieldName);
                    }
                }
            }

        } catch (Exception e) {
//            throw new RuntimeException(e);

            // 如果发生异常，设置请求属性以显示错误信息
            req.setAttribute("message", "错误信息: " + e.getMessage());
        } finally {
        }

        // 转发请求到 message.jsp 页面，以显示上传结果
        getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
    }
}
